package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 *
 * @Author Yang
 * @Date 2023/3/1 18:09
 */

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session用户信息
        Employee attribute = (Employee) request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);

        if(attribute == null){
            ResultInfo notlogin = ResultInfo.error("NOTLOGIN");
            String string = JSON.toJSONString(notlogin);
            response.getWriter().write(string);
            return false;
        }

        EmployeeHolder.set(attribute);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}
